package com.corpgovernment.travelstandard.controller;

import cn.hutool.core.lang.Tuple;
import com.corpgovernment.api.organization.model.post.PostVo;
import com.corpgovernment.api.organization.utils.CommonUtil;
import com.corpgovernment.api.travelstandard.enums.*;
import com.corpgovernment.api.travelstandard.vo.*;
import com.corpgovernment.api.travelstandard.vo.MbTravelstandFlightCabinVo;
import com.corpgovernment.api.travelstandard.vo.MbTravelstandReasonCodeVo;
import com.corpgovernment.api.travelstandard.vo.RCListVo;
import com.corpgovernment.api.travelstandard.vo.TravelStandardPostVo;
import com.corpgovernment.api.travelstandard.vo.TravelStandardSoaRequestVo;
import com.corpgovernment.api.travelstandard.vo.intlflight.IntlFlightManageVo;
import com.corpgovernment.api.travelstandard.vo.intlflight.MbTravelstandIntlFlightVo;
import com.corpgovernment.api.travelstandard.vo.request.IntlFlightShowRequest;
import com.corpgovernment.api.travelstandard.vo.request.IntlFlightTravelStandardSoaRequestListVo;
import com.corpgovernment.api.travelstandard.vo.response.FlightIntlTravelStandardShowTextResponse;
import com.corpgovernment.api.travelstandard.vo.response.IntlFlightShowResponse;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.corpgovernment.common.utils.DateUtil;
import com.corpgovernment.organization.constant.CommonConst;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.travelstandard.impl.MbTravelstandIntlFlightTimeService;
import com.corpgovernment.travelstandard.impl.MbTravelstandFlightCabinService;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.corpgovernment.organization.constant.CommonConst;
import com.corpgovernment.organization.service.IPostService;
import com.corpgovernment.travelstandard.entity.db.TravelStandardPost;
import com.corpgovernment.travelstandard.impl.MbTravelstandIntlFlightService;
import com.corpgovernment.travelstandard.impl.MbTravelstandReasonCodeService;
import com.corpgovernment.travelstandard.impl.TravelStandardPostService;
import com.corpgovernment.travelstandard.utils.BeanConverUtil;
import com.corpgovernment.travelstandard.vo.IntlFlightTravelStandardResponseVO;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("intlFlightTravelStandardManage")
public class IntlFlightTravelStandardManageController {

    private final static String INTL_FLIGHT_TRAVEL_STANDARD_DEFAULT_NAME = "国际机票差旅标准";

    @Autowired
    private MbTravelstandIntlFlightService mbTravelstandIntlFlightService;
    @Autowired
    private TravelStandardPostService standPostService;
	@Autowired
	private IPostService postService;
    @Autowired
    private MbTravelstandReasonCodeService travelstandReasonCodeService;
    @Autowired
    private MbTravelstandFlightCabinService standFlightCabinService;
    @Autowired
    private MbTravelstandIntlFlightTimeService mbTravelstandIntlFlightTimeService;
    /**
     * 差标属于公司，不属于部门
     * 新增机票差标
     * 请求json：{title（机票名称）: "123", orgid（组织id）: "zjiXyTVVmY"}
     * @return
     */
    @RequestMapping("toAdd")
    public JSONResult toAddFlightTravelStandard(@RequestBody IntlFlightManageVo intlFlightManageVo ) {
        String title = intlFlightManageVo.getTitle();
        //获取机票差标名称
        if (StringUtils.isBlank(title)) {
            title = INTL_FLIGHT_TRAVEL_STANDARD_DEFAULT_NAME;
        }
        //获取公司id
        String orgId = intlFlightManageVo.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "公司id不能为空");
        }
        MbTravelstandIntlFlightVo mbTravelstandIntlFlightVo = new MbTravelstandIntlFlightVo(
                null,
                orgId,
                title,
                IntlFlightSwitchEnum.ClassSwitch.N.getCode(),
                ClazzEnum.Y.getCode(),
                ControlTypeEnum.F.getCode(),
                IntlFlightSwitchEnum.LowpriceSwitch.N.getCode(),
                180,
                DateUtil.stringToDate("00:00",DateUtil.DF_HM),
                DateUtil.stringToDate("23:59",DateUtil.DF_HM),
                ControlTypeEnum.F.getCode(),
                FlightSwitchEnum.AdvancedbookSwitch.N.getCode(),
                3,
                ControlTypeEnum.F.getCode()
        );
        mbTravelstandIntlFlightVo.setLowpriceFloatType(FlightSwitchEnum.LowPriceFloatTypeSwitch.A.getCode());
        mbTravelstandIntlFlightVo.setLowpriceFloatAmount(0);
        mbTravelstandIntlFlightVo.setLowpriceFloatNum(0);
        mbTravelstandIntlFlightVo.setAirportComparePrice(CommonConst.FALSE);
        mbTravelstandIntlFlightVo.setProductSwitch("E");
        mbTravelstandIntlFlightVo.setAmountControlSwitch(IntlFlightSwitchEnum.AmountControlSwitch.N.getCode());
        mbTravelstandIntlFlightVo.setAmountControlNum(100);
        mbTravelstandIntlFlightVo.setAmountControlCurrency(CommonConst.CNY_CODE);
        mbTravelstandIntlFlightVo.setAmountControlType(ControlTypeEnum.F.getCode());

        // 时间管控
        mbTravelstandIntlFlightVo.setTimeSwitch(IntlFlightSwitchEnum.TimeSwitch.N.getCode());
        mbTravelstandIntlFlightVo.setTimeChooseType(TimeChooseTypeEnum.C.getCode());
        mbTravelstandIntlFlightVo.setTimeControlType(ControlTypeEnum.F.getCode());
        // 协议价管控
        mbTravelstandIntlFlightVo.setProtocolPriceSwitch(IntlFlightSwitchEnum.ProtocolPriceSwitch.N.getCode());
        mbTravelstandIntlFlightVo.setProtocolPriceControlType(ControlTypeEnum.C.getCode());
        mbTravelstandIntlFlightVo.setAmountControlSwitch(IntlFlightSwitchEnum.AmountControlSwitch.N.getCode());
        mbTravelstandIntlFlightVo.setAmountControlNum(100);
        mbTravelstandIntlFlightVo.setAmountControlCurrency(CommonConst.CNY_CODE);
        mbTravelstandIntlFlightVo.setAmountControlType(ControlTypeEnum.F.getCode());

        mbTravelstandIntlFlightService.insertIntlFlightTravelStandard(mbTravelstandIntlFlightVo);
        List<MbTravelstandReasonCodeVo> travelstandReasonCodeVos = travelstandReasonCodeService.list(new MbTravelstandReasonCodeVo().setTsId(mbTravelstandIntlFlightVo.getId()).setTsType(TravelStandardTypeEnum.IntlFlight.getCode()));
        Map<String,Object> returnMap = new HashMap<>();
        List<MbTravelstandFlightCabinVo> standFlightCabinVos = standFlightCabinService.list(
                new MbTravelstandFlightCabinVo().setTsFlightId(mbTravelstandIntlFlightVo.getId())
                        .setTsType(TravelStandardTypeEnum.IntlFlight.getCode()));

        // 时间管控：获取管控时间段
        List<MbTravelstandIntlFlightTimeVo> mbTravelstandIntlFlightTimeVos = mbTravelstandIntlFlightTimeService.list(new MbTravelstandIntlFlightTimeVo().setTsIntlFlightId(mbTravelstandIntlFlightVo.getId()));
        returnMap.put("domAirTicket", BeanConverUtil.travelstandIntlFlightVoToIntlFlightManageVo(
                mbTravelstandIntlFlightVo,null, travelstandReasonCodeVos, standFlightCabinVos,mbTravelstandIntlFlightTimeVos));
        return JSONResult.success(returnMap);
    }

    /**
     * 更新机票差标属性
     * @param vo
     * @return
     */
    @RequestMapping("save")
    public JSONResult updateFlightTravelStandardProperty(@RequestBody IntlFlightManageVo vo) {
        mbTravelstandIntlFlightService.updateIntlFlightTravelStandardProperty(vo);
        return JSONResult.ok();
    }

    /**
     * 更新差标名称
     */
    @RequestMapping("updateStandardName")
    public JSONResult updateStandardName(@RequestBody IntlFlightManageVo intlFlightManageVo) {
        String id = intlFlightManageVo.getId();
        if (StringUtils.isBlank(id)){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "id");
        }
        String title = intlFlightManageVo.getTitle();
        if (StringUtils.isBlank(title)){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "title");
        }
        mbTravelstandIntlFlightService.updateStandardName(Long.valueOf(id),title);
        return JSONResult.ok();
    }

    /**
     * 删除机票差标
     * @return
     */
    @RequestMapping("delete")
    public JSONResult deleteFlightTravelStandard(@RequestBody IntlFlightManageVo intlFlightManageVo) {
        String id = intlFlightManageVo.getId();
        if (StringUtils.isBlank(id)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "id");
        }
        mbTravelstandIntlFlightService.deleteIntlFlightTravelStandard(Long.valueOf(id));
        return JSONResult.ok();
    }

    /**
     * 获取全部机票差标
     * @return
     */
    @RequestMapping("get")
    public JSONResult<IntlFlightTravelStandardResponseVO> getFlightTravelStandard(@RequestBody IntlFlightManageVo intlFlightManageVo) {
        String orgId = intlFlightManageVo.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_ID_NULL);
        }
        //通过soa接口获取全部岗位
        List<PostVo> posts = postService.listPostByOrgId(orgId);
        //已被选岗位
        List<TravelStandardPostVo> travelStandardPostVos = standPostService.selectByTsTypeAndOrgId(TravelStandardTypeEnum.IntlFlight.getCode(),orgId);
        List<Long> jobScope = new ArrayList<>();
        for (TravelStandardPostVo travelStandardPostVo : travelStandardPostVos) {
            jobScope.add(travelStandardPostVo.getPostid());
        }
        //该组织下下所有机票差标
        List<IntlFlightManageVo> domAirTicket = mbTravelstandIntlFlightService.listIntlFlightTravelStandard(new MbTravelstandIntlFlightVo(){{
            setOrgId(orgId);
        }});
        return JSONResult.success(IntlFlightTravelStandardResponseVO.create(domAirTicket, jobScope, posts));
    }


    /**
     * 更新RC
     * @param rcListVo 传输对象
     * @return
     */
    @RequestMapping("updateRc")
    public JSONResult updateRc(@RequestBody RCListVo rcListVo) {
        rcListVo.setTsType(TravelStandardTypeEnum.IntlFlight.getCode());
        travelstandReasonCodeService.updateTravelstandReasonCode(rcListVo);
        return JSONResult.ok();
    }

    /**
     * SOA-根据uid、orgId查询国际机票差标
     */
    @RequestMapping("getIntlFlightTravelStandard")
    public JSONResult<IntlFlightManageVo> getIntlFlightTravelStandard(@RequestParam(value = "uid") String uid, @RequestParam(value = "orgId") String orgId){
        MbTravelstandIntlFlightVo mbTravelstandIntlFlightVo = mbTravelstandIntlFlightService.getMbTravelstandIntlFlightVoByuidAndOrgId(uid, orgId, null);
        if (mbTravelstandIntlFlightVo == null){
            return new JSONResult<>(null);
        }
        //获得差标关联的岗位
        List<TravelStandardPost> travelStandardPosts = standPostService.list(new TravelStandardPostVo() {{
            setTsid(mbTravelstandIntlFlightVo.getId());
            setTstype(TravelStandardTypeEnum.IntlFlight.getCode());
        }});
        //获得差标关联的RC
        List<MbTravelstandReasonCodeVo> travelstandReasonCodeVos = travelstandReasonCodeService.list(new MbTravelstandReasonCodeVo() {{
            setTsId(mbTravelstandIntlFlightVo.getId());
            setTsType(TravelStandardTypeEnum.IntlFlight.getCode());
        }});

        List<MbTravelstandFlightCabinVo> standFlightCabinVos = standFlightCabinService.list(
                new MbTravelstandFlightCabinVo().setTsFlightId(mbTravelstandIntlFlightVo.getId())
                        .setTsType(TravelStandardTypeEnum.IntlFlight.getCode()));

        //获得差标关联的时间信息
        List<MbTravelstandIntlFlightTimeVo> mbTravelstandIntlFlightTimeVos = mbTravelstandIntlFlightTimeService.list(new MbTravelstandIntlFlightTimeVo().setTsIntlFlightId(mbTravelstandIntlFlightVo.getId()));
        IntlFlightManageVo intlFlightManageVo = BeanConverUtil.travelstandIntlFlightVoToIntlFlightManageVo(
                mbTravelstandIntlFlightVo,
                CommonUtil.copyList(travelStandardPosts, TravelStandardPostVo.class),
                travelstandReasonCodeVos,
                standFlightCabinVos,
                mbTravelstandIntlFlightTimeVos
        );
        return new JSONResult<>(intlFlightManageVo);
    }
    /**
     * SOA-根据uid、orgId批量查询国际机票差标
     */
    @PostMapping("getIntlFlightTravelStandardList")
    public JSONResult<Map<String, IntlFlightManageVo>> getIntlFlightTravelStandardList(IntlFlightTravelStandardSoaRequestListVo request){
        if (request == null || CollectionUtils.isEmpty(request.getRequestVoList())){
            return new JSONResult<>(Collections.emptyMap());
        }
        return new JSONResult<>(request.getRequestVoList().stream().map(t->{
            JSONResult<IntlFlightManageVo> response = this.getIntlFlightTravelStandard(t.getUserId(), t.getOrgId());
            if (response != null && response.getData() != null){
                return new Tuple(t.getUserId(), response.getData());
            }
            return new Tuple(t.getUserId(), response.getData());
        }).collect(Collectors.toMap(t -> t.get(0), t -> t.get(1), (t1, t2) -> t1)));



    }

    /**
     *
     */
    @RequestMapping("travelStandardShow")
    public JSONResult<IntlFlightShowResponse> travelStandardShow(@RequestBody IntlFlightShowRequest request, BaseUserInfo baseUserInfo){
		request.setBaseUserInfo(baseUserInfo);
        return JSONResult.success(mbTravelstandIntlFlightService.intlFlightShow(request));
    }

    @RequestMapping("travelStandardShowSoa")
    public JSONResult<IntlFlightShowResponse> travelStandardShowSoa(@RequestBody IntlFlightShowRequest request){
        return JSONResult.success(mbTravelstandIntlFlightService.intlFlightShow(request));
    }

    @RequestMapping("/travelStandardShowText")
    public JSONResult<FlightIntlTravelStandardShowTextResponse> travelStandardShowText(@RequestBody TravelStandardSoaRequestVo request) {
        return JSONResult.success(mbTravelstandIntlFlightService.flightIntlTravelStandardShowText(request));
    }
}
